<template>
   
  <div class="schedule-page">
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" label-width="0">
        <el-form-item>
          <el-input
            v-model="searchForm.name"
            placeholder="请输入班次名称"
            clearable
            style="width: 220px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="table-card">
      <div class="table-toolbar">
        <h2>排班计划</h2>
        <div>
          <el-button type="primary" @click="openCreateDialog">新增</el-button>
          <el-button
            type="danger"
            :disabled="!selectedIds.length"
            @click="handleBatchDelete"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="workingname" label="班次名称" min-width="140">
          <template #default="{ row }">
            <span>{{ row.workingname || '-' }}</span>
            <el-tag v-if="row.isdefault" type="warning" size="small" style="margin-left: 8px">
              默认
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="workingjname" label="班次简称" min-width="120">
          <template #default="{ row }">
            {{ row.workingjname || '-' }}
          </template>
        </el-table-column>
        <el-table-column label="班次颜色" min-width="140">
          <template #default="{ row }">
            <div v-if="row.workingcolor" class="color-cell">
              <el-dropdown trigger="click" @command="() => {}">
                <span class="color-display">
                  <span class="color-dot" :style="{ background: row.workingcolor }" />
                  <el-icon><ArrowDown /></el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>{{ row.workingcolor }}</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="工作时间" min-width="180">
          <template #default="{ row }">
            {{ formatWorkingTime(row.createtimes, row.endtimes) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="openEditDialog(row)">
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.totalCount"
          v-model:current-page="pagination.pageindex"
          v-model:page-size="pagination.pagesize"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="`${dialogTitle}_${dialogForm.shiftMode || '两班倒'}`"
      width="1200px"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
          <el-form
            ref="dialogFormRef"
            :model="dialogForm"
            :rules="dialogRules"
            label-width="120px"
            style="margin-top: 20px"
          >
            <el-form-item label="计划编号" prop="planCode">
              <el-input
                v-model="dialogForm.planCode"
                placeholder="请输入"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="系统编号">
              <el-switch v-model="dialogForm.isSystemCode" />
            </el-form-item>
            <el-form-item label="计划名称" prop="planName">
              <el-input
                v-model="dialogForm.planName"
                placeholder="请输入"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
              <el-date-picker
                v-model="dialogForm.startTime"
                type="date"
                placeholder="yyyy/mm/dd"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
              <el-date-picker
                v-model="dialogForm.endTime"
                type="date"
                placeholder="yyyy/mm/dd"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
                style="width: 300px"
              />
            </el-form-item>
            <el-form-item label="工作日历">
              <el-input
                v-model="dialogForm.workCalendarName"
                placeholder="请选择工作日历"
                readonly
                style="width: 300px; cursor: pointer"
                @click="openCalendarDialog"
              >
                <template #suffix>
                  <el-icon style="cursor: pointer"><Grid /></el-icon>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="轮班方式" prop="shiftMode">
              <el-radio-group v-model="dialogForm.shiftMode" @change="handleShiftModeChange">
                <el-radio value="固定">固定</el-radio>
                <el-radio value="两班倒">两班倒</el-radio>
                <el-radio value="三班倒">三班倒</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="倒班方式">
              <el-select
                v-model="dialogForm.shiftReverseMode"
                placeholder="请选择倒班方式"
                style="width: 300px"
              >
                <el-option label="顺倒" value="顺倒" />
                <el-option label="反倒" value="反倒" />
              </el-select>
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="dialogForm.remark"
                type="textarea"
                :rows="3"
                placeholder="请输入"
                style="width: 500px"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <!-- 班次信息 -->
        <el-tab-pane label="班次信息" name="shift">
          <div style="margin: 20px 0">
            <el-alert
              v-if="dialogForm.shiftMode === '两班倒'"
              type="warning"
              :closable="false"
              style="margin-bottom: 16px"
            >
              只能选择两个班次
            </el-alert>
            <el-alert
              v-else-if="dialogForm.shiftMode === '三班倒'"
              type="warning"
              :closable="false"
              style="margin-bottom: 16px"
            >
              只能选择三个班次
            </el-alert>
            <div style="margin-bottom: 16px">
              <el-button type="primary" @click="openShiftSelectDialog">添加</el-button>
            <el-button
              :disabled="selectedShiftsInTable.length === 0"
              @click="handleRemoveShifts"
            >
              移除
            </el-button>
            </div>
            <el-table
              :data="selectedShifts"
              border
              @selection-change="handleShiftSelectionChange"
            >
              <el-table-column type="selection" width="50" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="workingname" label="班次名称" min-width="140" />
              <el-table-column label="开始时间" min-width="120">
                <template #default="{ row }">
                  {{ formatTime(row.createtimes) }}
                </template>
              </el-table-column>
              <el-table-column label="结束时间" min-width="120">
                <template #default="{ row }">
                  {{ formatTime(row.endtimes) }}
                </template>
              </el-table-column>
              <el-table-column label="备注" min-width="200">
                <template #default="{ row, $index }">
                  <el-input
                    v-model="row.remark"
                    placeholder="请输入备注"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button link type="danger" @click="handleRemoveShift(row)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <!-- 班组信息 -->
        <el-tab-pane label="班组信息" name="team">
          <div style="margin: 20px 0">
            <div style="margin-bottom: 16px">
              <el-button type="primary" @click="openTeamSelectDialog">添加</el-button>
            <el-button
              :disabled="selectedTeamsInTable.length === 0"
              @click="handleRemoveTeams"
            >
              移除
            </el-button>
            </div>
            <el-table
              :data="selectedTeams"
              border
              @selection-change="handleTeamSelectionChange"
            >
              <el-table-column type="selection" width="50" />
              <el-table-column type="index" label="序号" width="60" />
              <el-table-column prop="teamname" label="班组名称" min-width="140" />
              <el-table-column prop="teamnumber" label="班组编码" min-width="140" />
              <el-table-column prop="typename" label="班组类型" min-width="120" />
              <el-table-column prop="fzr" label="负责人" min-width="120" />
              <el-table-column label="备注" min-width="200">
                <template #default="{ row }">
                  <el-input
                    v-model="row.remark"
                    placeholder="请输入备注"
                    size="small"
                  />
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100">
                <template #default="{ row }">
                  <el-button link type="danger" @click="handleRemoveTeam(row)">
                    移除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="handleSubmit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 工作日历选择对话框 -->
    <el-dialog
      v-model="calendarDialogVisible"
      title="选择工作日历"
      width="800px"
    >
      <el-table
        :data="calendarList"
        border
        @row-click="handleCalendarSelect"
      >
        <el-table-column prop="calendarname" label="日历名称" />
        <el-table-column prop="calendartype" label="日历类型" />
      </el-table>
      <template #footer>
        <el-button @click="calendarDialogVisible = false">取消</el-button>
      </template>
    </el-dialog>

    <!-- 班次选择对话框 -->
    <el-dialog
      v-model="shiftSelectDialogVisible"
      title="选择班次"
      width="800px"
    >
      <el-table
        :data="shiftList"
        border
        @selection-change="handleShiftTableSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="workingname" label="班次名称" />
        <el-table-column prop="workingjname" label="班次简称" />
        <el-table-column label="开始时间">
          <template #default="{ row }">
            {{ formatTime(row.createtimes) }}
          </template>
        </el-table-column>
        <el-table-column label="结束时间">
          <template #default="{ row }">
            {{ formatTime(row.endtimes) }}
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="shiftSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleShiftConfirm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 班组选择对话框 -->
    <el-dialog
      v-model="teamSelectDialogVisible"
      title="选择班组"
      width="1000px"
    >
      <el-table
        :data="teamList"
        border
        @selection-change="handleTeamTableSelectionChange"
      >
        <el-table-column type="selection" width="50" />
        <el-table-column prop="teamname" label="班组名称" />
        <el-table-column prop="teamnumber" label="班组编码" />
        <el-table-column prop="typename" label="班组类型" />
        <el-table-column prop="fzr" label="负责人" />
      </el-table>
      <template #footer>
        <el-button @click="teamSelectDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleTeamConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { ArrowDown, Grid } from '@element-plus/icons-vue'
import https from '@/Http/http'
import dayjs from 'dayjs'

interface Schedule {
  id: number
  planCode?: string
  planName?: string
  startTime?: string | Date
  endTime?: string | Date
  workCalendarId?: number
  shiftMode?: string
  shiftReverseMode?: string
  remark?: string
  workingname?: string
  workingjname?: string
  workingcolor?: string
  createtimes?: string | Date
  endtimes?: string | Date
  isdefault?: boolean
}

interface ScheduleDetail extends Schedule {
  workCalendarName?: string
  shifts?: WorkingShift[]
  teams?: WorkTeam[]
}

interface WorkingShift {
  id: number
  workingname: string
  workingjname?: string
  createtimes?: string | Date
  endtimes?: string | Date
  remark?: string
}

interface WorkTeam {
  id: number
  teamname: string
  teamnumber: string
  typename?: string
  fzr: string
  remark?: string
}

interface WorkingCalendar {
  id: number
  calendarname: string
  calendartype?: string
}


const loading = ref(false)
const tableData = ref<Schedule[]>([])
const multipleSelection = ref<Schedule[]>([])

const pagination = reactive({
  pageindex: 1,
  pagesize: 10,
  totalCount: 0
})

const searchForm = reactive({
  name: ''
})

const selectedIds = computed(() => multipleSelection.value.map(item => item.id))

const getStatusCode = (payload: any) => payload?.code ?? payload?.Code
const getPayloadData = <T = any>(payload: any): T =>
  (payload?.data ?? payload?.Data) as T
const getPayloadMsg = (payload: any): string =>
  payload?.msg ?? payload?.Msg ?? ''
const getTotalCount = (payload: any) =>
  payload?.totalCount ?? payload?.TotalCount ?? 0

const formatWorkingTime = (startTime?: string | Date, endTime?: string | Date) => {
  if (!startTime || !endTime) return '-'
  try {
    const start = dayjs(startTime).format('HH:mm')
    const end = dayjs(endTime).format('HH:mm')
    return `${start}~${end}`
  } catch {
    return '-'
  }
}

const fetchSchedules = async () => {
  loading.value = true
  try {
    const params = {
      pageindex: pagination.pageindex,
      pagesize: pagination.pagesize,
      name: searchForm.name || undefined
    }
    const { data } = await https.Reads.get("/Working/ShowSchedule", { params })
    if (getStatusCode(data) === 1) {
      tableData.value = getPayloadData<Schedule[]>(data) ?? []
      pagination.totalCount = getTotalCount(data)
    } else {
      ElMessage.error(getPayloadMsg(data) || '获取排班计划失败')
    }
  } catch (error: any) {
    console.error('fetchSchedules error', error)
    ElMessage.error(error?.message || '获取排班计划失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.pageindex = 1
  fetchSchedules()
}

const handleReset = () => {
  searchForm.name = ''
  pagination.pageindex = 1
  fetchSchedules()
}

const handleSizeChange = (val: number) => {
  pagination.pagesize = val
  pagination.pageindex = 1
  fetchSchedules()
}

const handlePageChange = (val: number) => {
  pagination.pageindex = val
  fetchSchedules()
}

const handleSelectionChange = (rows: Schedule[]) => {
  multipleSelection.value = rows
}

const dialogVisible = ref(false)
const dialogTitle = ref('新增排班计划')
const activeTab = ref('basic')
const dialogFormRef = ref<FormInstance>()
const saving = ref(false)
const editingPlanId = ref<number | null>(null)

const dialogForm = reactive({
  planCode: '',
  isSystemCode: false,
  planName: '',
  startTime: '',
  endTime: '',
  workCalendarId: undefined as undefined | number,
  workCalendarName: '',
  shiftMode: '两班倒',
  shiftReverseMode: '',
  remark: ''
})

const dialogRules: FormRules = {
  planCode: [{ required: true, message: '请输入计划编号', trigger: 'blur' }],
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
  endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
  shiftMode: [{ required: true, message: '请选择轮班方式', trigger: 'change' }]
}

// 班次相关
const selectedShifts = ref<(WorkingShift & { remark?: string })[]>([])
const selectedShiftIds = ref<number[]>([])
const shiftSelectDialogVisible = ref(false)
const shiftList = ref<WorkingShift[]>([])
const shiftTableSelection = ref<WorkingShift[]>([])
const selectedShiftsInTable = ref<(WorkingShift & { remark?: string })[]>([])

// 班组相关
const selectedTeams = ref<(WorkTeam & { remark?: string })[]>([])
const selectedTeamIds = ref<number[]>([])
const teamSelectDialogVisible = ref(false)
const teamList = ref<WorkTeam[]>([])
const teamTableSelection = ref<WorkTeam[]>([])
const selectedTeamsInTable = ref<(WorkTeam & { remark?: string })[]>([])

// 工作日历相关
const calendarDialogVisible = ref(false)
const calendarList = ref<WorkingCalendar[]>([])

const formatTime = (time?: string | Date) => {
  if (!time) return '-'
  try {
    return dayjs(time).format('HH:mm')
  } catch {
    return '-'
  }
}

const formatDateValue = (time?: string | Date) => {
  if (!time) return ''
  try {
    return dayjs(time).format('YYYY-MM-DD')
  } catch {
    return ''
  }
}

const mapScheduleDetail = (detail: any): ScheduleDetail => {
  const shifts = (detail?.shifts ?? detail?.Shifts ?? []).map((item: any) => ({
    id: item?.id ?? 0,
    workingname: item?.workingname ?? item?.Workingname ?? '',
    workingjname: item?.workingjname ?? item?.Workingjname ?? '',
    workingcolor: item?.workingcolor ?? item?.Workingcolor ?? '',
    createtimes: item?.createtimes ?? item?.Createtimes ?? '',
    endtimes: item?.endtimes ?? item?.Endtimes ?? '',
    remark: item?.remark ?? ''
  })) as WorkingShift[]

  const teams = (detail?.teams ?? detail?.Teams ?? []).map((item: any) => ({
    id: item?.id ?? 0,
    teamname: item?.teamname ?? item?.Teamname ?? '',
    teamnumber: item?.teamnumber ?? item?.Teamnumber ?? '',
    typename: item?.typename ?? item?.Typename ?? '',
    fzr: item?.fzr ?? item?.Fzr ?? '',
    remark: item?.remark ?? item?.desc ?? item?.Desc ?? ''
  })) as WorkTeam[]

  return {
    id: detail?.id ?? 0,
    planCode: detail?.planCode ?? detail?.PlanCode ?? '',
    planName: detail?.planName ?? detail?.PlanName ?? '',
    startTime: detail?.startTime ?? detail?.StartTime ?? '',
    endTime: detail?.endTime ?? detail?.EndTime ?? '',
    workCalendarId: detail?.workCalendarId ?? detail?.WorkCalendarId,
    workCalendarName: detail?.workCalendarName ?? detail?.WorkCalendarName ?? '',
    shiftMode: detail?.shiftMode ?? detail?.ShiftMode ?? '两班倒',
    shiftReverseMode: detail?.shiftReverseMode ?? detail?.ShiftReverseMode ?? '',
    remark: detail?.remark ?? detail?.Remark ?? '',
    shifts,
    teams
  } as ScheduleDetail
}

const handleShiftModeChange = (value: string) => {
  // 根据轮班方式限制班次数量
  if (value === '两班倒' && selectedShifts.value.length > 2) {
    ElMessage.warning('两班倒只能选择2个班次，已自动移除多余的班次')
    selectedShifts.value = selectedShifts.value.slice(0, 2)
    selectedShiftIds.value = selectedShifts.value.map(s => s.id)
  } else if (value === '三班倒' && selectedShifts.value.length > 3) {
    ElMessage.warning('三班倒只能选择3个班次，已自动移除多余的班次')
    selectedShifts.value = selectedShifts.value.slice(0, 3)
    selectedShiftIds.value = selectedShifts.value.map(s => s.id)
  }
}

const openCreateDialog = async () => {
  dialogTitle.value = '新增排班计划'
  activeTab.value = 'basic'
  editingPlanId.value = null
  resetDialogForm()
  await Promise.all([fetchCalendars(), fetchShiftList(), fetchTeamList()])
  dialogVisible.value = true
}

const resetDialogForm = () => {
  dialogForm.planCode = ''
  dialogForm.isSystemCode = false
  dialogForm.planName = ''
  dialogForm.startTime = ''
  dialogForm.endTime = ''
  dialogForm.workCalendarId = undefined
  dialogForm.workCalendarName = ''
  dialogForm.shiftMode = '两班倒'
  dialogForm.shiftReverseMode = ''
  dialogForm.remark = ''
  selectedShifts.value = []
  selectedShiftIds.value = []
  selectedShiftsInTable.value = []
  selectedTeams.value = []
  selectedTeamIds.value = []
  selectedTeamsInTable.value = []
  editingPlanId.value = null
  dialogFormRef.value?.clearValidate()
}

const handleDialogClose = () => {
  resetDialogForm()
}

const fetchCalendars = async () => {
  try {
    const { data } = await https.Reads.get("/Working/ShowWorkingCalendar", {
      params: { pageindex: 1, pagesize: 100 }
    })
    if (getStatusCode(data) === 1) {
      calendarList.value = getPayloadData<WorkingCalendar[]>(data) ?? []
    }
  } catch (error) {
    console.error('fetchCalendars error', error)
  }
}

const fetchShiftList = async () => {
  try {
    const { data } = await https.Reads.get("/Working/ShowWorkingci", {
      params: { pageindex: 1, pagesize: 1000 }
    })
    if (getStatusCode(data) === 1) {
      shiftList.value = getPayloadData<WorkingShift[]>(data) ?? []
    }
  } catch (error) {
    console.error('fetchShiftList error', error)
  }
}

const fetchTeamList = async () => {
  try {
    const { data } = await https.Reads.get("/Working/ShowWork", {
      params: { pageindex: 1, pagesize: 1000 }
    })
    if (getStatusCode(data) === 1) {
      teamList.value = getPayloadData<WorkTeam[]>(data) ?? []
    }
  } catch (error) {
    console.error('fetchTeamList error', error)
  }
}

const fetchScheduleDetail = async (id: number) => {
  try {
    const { data } = await https.Reads.get("/Working/GetScheduleDetail", {
      params: { id }
    })
    if (getStatusCode(data) === 1) {
      return getPayloadData<ScheduleDetail>(data)
    }
    throw new Error(getPayloadMsg(data) || '获取排班计划详情失败')
  } catch (error: any) {
    console.error('fetchScheduleDetail error', error)
    ElMessage.error(error?.message || '获取排班计划详情失败')
    throw error
  }
}

const openCalendarDialog = () => {
  calendarDialogVisible.value = true
}

const handleCalendarSelect = (row: WorkingCalendar) => {
  dialogForm.workCalendarId = row.id
  dialogForm.workCalendarName = row.calendarname
  calendarDialogVisible.value = false
}

const openShiftSelectDialog = () => {
  const maxShifts = dialogForm.shiftMode === '两班倒' ? 2 : dialogForm.shiftMode === '三班倒' ? 3 : 999
  if (selectedShifts.value.length >= maxShifts) {
    ElMessage.warning(`最多只能选择${maxShifts}个班次`)
    return
  }
  shiftTableSelection.value = []
  shiftSelectDialogVisible.value = true
}

const handleShiftTableSelectionChange = (rows: WorkingShift[]) => {
  shiftTableSelection.value = rows
}

const handleShiftConfirm = () => {
  const maxShifts = dialogForm.shiftMode === '两班倒' ? 2 : dialogForm.shiftMode === '三班倒' ? 3 : 999
  const availableSlots = maxShifts - selectedShifts.value.length
  
  if (shiftTableSelection.value.length === 0) {
    ElMessage.warning('请选择班次')
    return
  }

  if (shiftTableSelection.value.length > availableSlots) {
    ElMessage.warning(`最多只能再选择${availableSlots}个班次`)
    return
  }

  const newShifts = shiftTableSelection.value
    .filter(s => !selectedShiftIds.value.includes(s.id))
    .map(s => ({ ...s, remark: '' }))
  
  selectedShifts.value.push(...newShifts)
  selectedShiftIds.value = selectedShifts.value.map(s => s.id)
  shiftSelectDialogVisible.value = false
}

const handleShiftSelectionChange = (rows: (WorkingShift & { remark?: string })[]) => {
  selectedShiftsInTable.value = rows
}

const handleRemoveShift = (row: WorkingShift) => {
  const index = selectedShifts.value.findIndex(s => s.id === row.id)
  if (index > -1) {
    selectedShifts.value.splice(index, 1)
    selectedShiftIds.value = selectedShifts.value.map(s => s.id)
  }
}

const handleRemoveShifts = () => {
  if (selectedShiftsInTable.value.length === 0) {
    ElMessage.warning('请先选择要移除的班次')
    return
  }
  const idsToRemove = selectedShiftsInTable.value.map(item => item.id)
  selectedShifts.value = selectedShifts.value.filter(item => !idsToRemove.includes(item.id))
  selectedShiftIds.value = selectedShifts.value.map(item => item.id)
  selectedShiftsInTable.value = []
}

const openTeamSelectDialog = () => {
  teamTableSelection.value = []
  teamSelectDialogVisible.value = true
}

const handleTeamTableSelectionChange = (rows: WorkTeam[]) => {
  teamTableSelection.value = rows
}

const handleTeamConfirm = () => {
  if (teamTableSelection.value.length === 0) {
    ElMessage.warning('请选择班组')
    return
  }

  const newTeams = teamTableSelection.value
    .filter(t => !selectedTeamIds.value.includes(t.id))
    .map(t => ({ ...t, remark: '' }))
  
  selectedTeams.value.push(...newTeams)
  selectedTeamIds.value = selectedTeams.value.map(t => t.id)
  teamSelectDialogVisible.value = false
}

const handleTeamSelectionChange = (rows: (WorkTeam & { remark?: string })[]) => {
  selectedTeamsInTable.value = rows
}

const handleRemoveTeam = (row: WorkTeam) => {
  const index = selectedTeams.value.findIndex(t => t.id === row.id)
  if (index > -1) {
    selectedTeams.value.splice(index, 1)
    selectedTeamIds.value = selectedTeams.value.map(t => t.id)
  }
}

const handleRemoveTeams = () => {
  if (selectedTeamsInTable.value.length === 0) {
    ElMessage.warning('请先选择要移除的班组')
    return
  }
  const idsToRemove = selectedTeamsInTable.value.map(item => item.id)
  selectedTeams.value = selectedTeams.value.filter(item => !idsToRemove.includes(item.id))
  selectedTeamIds.value = selectedTeams.value.map(item => item.id)
  selectedTeamsInTable.value = []
}

const handleSubmit = async () => {
  if (!dialogFormRef.value) return

  await dialogFormRef.value.validate(async (valid) => {
    if (!valid) return

    // 验证班次数量
    if (dialogForm.shiftMode === '两班倒') {
      if (selectedShifts.value.length !== 2) {
        ElMessage.warning('两班倒需要选择2个班次')
        activeTab.value = 'shift'
        return
      }
    } else if (dialogForm.shiftMode === '三班倒') {
      if (selectedShifts.value.length !== 3) {
        ElMessage.warning('三班倒需要选择3个班次')
        activeTab.value = 'shift'
        return
      }
    } else if (dialogForm.shiftMode === '固定') {
      if (selectedShifts.value.length === 0) {
        ElMessage.warning('固定方式需要至少选择1个班次')
        activeTab.value = 'shift'
        return
      }
    }

    if (selectedTeams.value.length === 0) {
      ElMessage.warning('请至少选择一个班组')
      activeTab.value = 'team'
      return
    }

    saving.value = true
    try {
      const payload = {
        id: editingPlanId.value || undefined,
        shiftMode: dialogForm.shiftMode,
        planCode: dialogForm.planCode,
        planName: dialogForm.planName,
        startTime: dialogForm.startTime,
        endTime: dialogForm.endTime,
        workCalendarId: dialogForm.workCalendarId || null,
        shiftReverseMode: dialogForm.shiftReverseMode || null,
        remark: dialogForm.remark || null,
        shiftIds: selectedShifts.value.map(s => s.id),
        teamIds: selectedTeams.value.map(t => t.id)
      }

      let data
      if (editingPlanId.value) {
        const response = await https.Writes.put("/Working/UpdateSchedule", payload)
        data = response.data
      } else {
        const response = await https.Writes.post("/Working/AddSchedule", payload)
        data = response.data
      }
      if (getStatusCode(data) === 1) {
        ElMessage.success(getPayloadMsg(data) || (editingPlanId.value ? '修改成功' : '新增成功'))
        dialogVisible.value = false
        fetchSchedules()
      } else {
        ElMessage.error(getPayloadMsg(data) || (editingPlanId.value ? '修改失败' : '新增失败'))
      }
    } catch (error: any) {
      console.error('submit error', error)
      ElMessage.error(error?.message || (editingPlanId.value ? '修改失败，请稍后重试' : '新增失败，请稍后重试'))
    } finally {
      saving.value = false
    }
  })
}

const openEditDialog = async (row: Schedule) => {
  activeTab.value = 'basic'
  dialogTitle.value = '编辑排班计划'
  resetDialogForm()
  try {
    await Promise.all([fetchCalendars(), fetchShiftList(), fetchTeamList()])
    const detailResponse = await fetchScheduleDetail(row.id)
    const detail = mapScheduleDetail(detailResponse)
    editingPlanId.value = detail.id
    dialogForm.planCode = detail.planCode || ''
    dialogForm.planName = detail.planName || ''
    dialogForm.startTime = formatDateValue(detail.startTime)
    dialogForm.endTime = formatDateValue(detail.endTime)
    dialogForm.workCalendarId = detail.workCalendarId ?? undefined
    dialogForm.workCalendarName = detail.workCalendarName || ''
    dialogForm.shiftMode = detail.shiftMode || '两班倒'
    dialogForm.shiftReverseMode = detail.shiftReverseMode || ''
    dialogForm.remark = detail.remark || ''
    selectedShifts.value = (detail.shifts ?? []).map(shift => ({ ...shift }))
    selectedShiftIds.value = selectedShifts.value.map(s => s.id)
    selectedTeams.value = (detail.teams ?? []).map(team => ({ ...team }))
    selectedTeamIds.value = selectedTeams.value.map(t => t.id)
    dialogFormRef.value?.clearValidate()
    dialogVisible.value = true
  } catch {
    // 错误已提示
  }
}

const handleDelete = async (row: Schedule) => {
  try {
    await ElMessageBox.confirm('确定要删除该排班计划吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const { data } = await https.Writes.delete("/Working/DeleteSchedule", {
      params: { id: row.id }
    })
    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '删除成功')
      fetchSchedules()
    } else {
      ElMessage.error(getPayloadMsg(data) || '删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('delete error', error)
      ElMessage.error(error?.message || '删除失败，请稍后重试')
    }
  }
}

const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedIds.value.length} 条数据吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    const { data } = await https.Writes.delete("/Working/BatchDeleteSchedule", {
      data: { ids: selectedIds.value }
    })
    if (getStatusCode(data) === 1) {
      ElMessage.success(getPayloadMsg(data) || '批量删除成功')
      fetchSchedules()
    } else {
      ElMessage.error(getPayloadMsg(data) || '批量删除失败')
    }
  } catch (error: any) {
    if (error !== 'cancel') {
      console.error('batch delete error', error)
      ElMessage.error(error?.message || '批量删除失败，请稍后重试')
    }
  }
}

onMounted(() => {
  fetchSchedules()
})
</script>

<style scoped lang="scss">
.schedule-page {
  padding: 20px;

  .filter-card {
    margin-bottom: 20px;
  }

  .table-card {
    .table-toolbar {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        font-size: 18px;
        font-weight: 500;
      }
    }

    .pagination-wrapper {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .color-cell {
    display: flex;
    align-items: center;

    .color-display {
      display: flex;
      align-items: center;
      gap: 4px;
      cursor: pointer;
      padding: 4px 8px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fff;

      .color-dot {
        width: 16px;
        height: 16px;
        border-radius: 2px;
        display: inline-block;
        border: 1px solid #ddd;
      }

      &:hover {
        border-color: #409eff;
      }
    }
  }
}
</style>

